package com.zdc.learn.netty.codec;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;

/**
 * 客户端 因为tcp 协议没有边界，所以数据在传输过程中会发生粘包和拆包问题 ，以下是解决粘包和拆包示例
 */
public class CodecClientHandler extends SimpleChannelInboundHandler<MessageStyle> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageStyle msg) throws Exception {

    }

    /**
     * 客户端一连接上触发此方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //客户端发送数据
        System.out.println("发送数据start.....................");
        for (int i=0;i<5;i++){
            String mesg = "哇哈哈哈！！！";
            byte[] content = mesg.getBytes(Charset.forName("UTF-8"));
            int len = content.length;

            //创建协议包
            MessageStyle messageStyle = new MessageStyle();
            messageStyle.setContent(content);
            messageStyle.setLen(len);
            ctx.writeAndFlush(messageStyle);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        System.out.println("异常信息:"+cause.getMessage());
    }
}
